/* Copyright (c) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package openbang.chatroom.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openbang.chatroom.service.util.CacheHelper;
import openbang.chatroom.service.vo.CacheKeyDefine;
import openbang.chatroom.service.vo.ChatGroupMsg;
import openbang.chatroom.service.vo.ChatMsg;



/**
 * 清理Cache里过期的数据
 * 
 * 调用者：cron.xml中配置   /cron/clearExpired
 * 
 * 必须注意：并发性
 * 
 * @author aibo zeng
 *
 */

@SuppressWarnings("serial")
public class CacheClearServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(CacheClearServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	 		throws IOException, ServletException {
		doPost(req,resp);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException, ServletException {	
		//处理 session
		
		//处理聊天群和消息
		HashSet<String> allGroup =  CacheHelper.getChatGroupAll();
		if(allGroup==null || allGroup.isEmpty()){
			return;
		}
		Collection<String> canRemoveChatGroupKey = new HashSet<String>();
		Iterator<String> iterator = allGroup.iterator();
		while(iterator.hasNext()){
			String groupKey = iterator.next();
			ChatGroupMsg gm = (ChatGroupMsg)CacheHelper.get(groupKey);
			if(gm==null){
				//对象没有了
				canRemoveChatGroupKey.add(groupKey);
				continue;
			}
			if(gm.isParticipantEmpty()){
				//没有参与人了,清理 --- 当群很多需要释放时,应该采用批量处理
				canRemoveChatGroupKey.add(groupKey);
				continue;
			}
			if(gm.getChatMsgs()==null || gm.getChatMsgs().size()<=0 ){
				//没有聊天内容
				continue;
			}
			Iterator<ChatMsg> iMsg = gm.getChatMsgs().iterator();
			Collection<ChatMsg> canRemoveChatMsg = new HashSet<ChatMsg>();
			while(iMsg.hasNext()){
				ChatMsg msg = iMsg.next();
				if( System.currentTimeMillis() - msg.getSendDate().getTime()>=gm.getMsgMaxLive()){
					//过期消息  记录
					canRemoveChatMsg.add(msg);
				}
			}
			if(!canRemoveChatMsg.isEmpty()){
				//过期消息 清理
				gm.getChatMsgs().removeAll(canRemoveChatMsg);
				//put 回 缓存
				CacheHelper.put(groupKey, gm);
			}					
		}
		//清理没有参与人的group
		if(!canRemoveChatGroupKey.isEmpty()){
			//CacheHelper.removeAll(canRemoveChatGroupKey, 1);
			allGroup.removeAll(canRemoveChatGroupKey);
    		CacheHelper.put(CacheKeyDefine.CHATGROUP_ALL,allGroup);			
			log.warning("remove chat group size="+canRemoveChatGroupKey.size());
		}
    }
	
	public static void main(String[] args){
		//测试遍历过程中,对“元素”删除的影响
		List<String>  testList = new ArrayList<String>();
		testList.add("U1");
		testList.add("U23");
		testList.add("U3");
		testList.add("U4");
		testList.add("U53");
		testList.add("U6");
		testList.add("U7");
		
		Iterator<String> itera = testList.iterator();
		int i = 0 ;
		while(itera.hasNext()){
			System.out.println("i="+i);
			String str = itera.next();//中途不能有删除
			if(str.indexOf("3")>=0){
				testList.remove(str);
			}
			i++;
		}
/*
 * 		i=0
		i=0
		i=0
		Exception in thread "main" java.util.ConcurrentModificationException
			at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
			at java.util.AbstractList$Itr.next(AbstractList.java:343)
			at openbang.account.service.impl.CacheClearServlet.main(CacheClearServlet.java:98)
*/		
	}
	
}
